package com.litxuf.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.log4j.Logger;

/**
 * Created by IntelliJ IDEA. User: ibm Date: 2007-3-16 Time: 15:37:40 To change
 * this template use File | Settings | File Templates.
 */
public class FileUtil {
	static Logger logger = Logger.getLogger(FileUtil.class);

	public static void saveUrlToFile(String urlstr, String abs_path,
			String jspCharSet) throws Exception {
		try {
			logger.debug("111");
			String filePath = abs_path;
			logger.debug("\nSave " + urlstr + " to " + filePath);
			File file = new File(filePath);
			if (!file.getParentFile().exists())
				file.getParentFile().mkdirs();

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			if (jspCharSet != null)
				bos.write(("<%@ page contentType=\"text/html;charset="
						+ jspCharSet + "\"%>").getBytes());
			URL url = new URL(urlstr);
			InputStream ins = url.openStream();

			BufferedInputStream bis = new BufferedInputStream(ins);
			byte[] data = new byte[1024];
			int pos = bis.read(data);
			while (pos > -1) {
				bos.write(data, 0, pos);
				pos = bis.read(data);
			}
			FileOutputStream fos = new FileOutputStream(filePath);
			bos.writeTo(fos);
			fos.close();

			bos.close();
			bis.close();
		} catch (Exception exp) {
			LoggerHelper.error(logger, exp);
			throw exp;
		}
	}

	public static byte[] getUrlContent(String urlstr) {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			URL url = new URL(urlstr);
			InputStream ins = url.openStream();

			byte[] data = new byte[1024];
			int pos = ins.read(data);
			while (pos > -1) {
				bos.write(data, 0, pos);
				pos = ins.read(data);
			}
			bos.close();
			ins.close();
			return bos.toByteArray();
		} catch (Exception exp) {
			LoggerHelper.error(logger, exp); // throw exp;
		}
		return null;
	}

	public static boolean delete(File file) {
		if (file.exists()) {
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (File sub : files)
					delete(sub);
			} else
				return file.delete();
			return file.delete();
		}
		return false;
	}

	public static boolean copyFile(File src, File target) {
		try {
			FileInputStream fis = new FileInputStream(src);
			FileOutputStream fos = new FileOutputStream(target);
			byte[] data = new byte[1024];
			int read = 0;
			while ((read = fis.read(data)) >= 0) {
				if (read > 0)
					fos.write(data, 0, read);
			}
			fis.close();
			fos.close();
			return true;
		} catch (IOException e) {
			LoggerHelper.error(logger, e); // To change body of catch statement
			// use
			// File | Settings | File Templates.
		}
		return false;
	}

	public static boolean copyDir(File src, File target) {
		if (!src.exists() || !src.isDirectory())
			return false;
		File[] files = src.listFiles();
		if (!target.exists())
			target.mkdirs();
		else if (!target.isDirectory())
			return false;
		if (files != null && files.length > 0)
			for (File sub : files) {
				File targetFile = new File(target.getAbsolutePath()
						+ File.separator + sub.getName());
				if (sub.isDirectory())
					copyDir(sub, targetFile);
				else
					copyFile(sub, targetFile);
			}
		return true;
	}

	public static boolean copy(File src, File target) {
		if (!src.exists())
			return false;
		if (src.isDirectory())
			return copyDir(src, target);
		else
			return copyFile(src, target);
	}

	public static byte[] saveStreamToByteArray(InputStream is) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] data = new byte[2048];
			int len = 0;
			while ((len = is.read(data)) > -1) {
				if (len > 0)
					baos.write(data, 0, len);
			}
			baos.close();
			is.close();
			return baos.toByteArray();
		} catch (IOException e) {
			LoggerHelper.error(logger, e);
		}
		return null;
	}

	public static boolean saveStreamToFile(InputStream is, File target_file) {
		try {
			FileOutputStream fos = new FileOutputStream(target_file);
			byte[] data = new byte[2048];
			int len = 0;
			while ((len = is.read(data)) > -1) {
				if (len > 0)
					fos.write(data, 0, len);
			}
			is.close();
			fos.close();
			return true;
		} catch (IOException e) {
			LoggerHelper.error(logger, e);
		}
		return false;
	}

	public static boolean saveStringToFile(String s, String targetFilePath,
			String encode) {
		try {
			FileOutputStream fos = new FileOutputStream(targetFilePath);
			if (encode != null)
				fos.write(s.getBytes(encode));
			else
				fos.write(s.getBytes());
			fos.close();
			return true;
		} catch (Exception e) {
			LoggerHelper.error(logger, e);
		}
		return false; // To change body of created methods use File | Settings
		// | File Templates.
	}

	/**
	 * 
	 * 生成静态页面 made by XuFeng 2007-8-17 下午05:12:23
	 * 
	 * @param eleUrl
	 * @param newPath
	 * @throws IOException
	 * @throws IOException
	 */

	public static void WriteDemo(String actionURL, String newPath)
			throws IOException {

		URL url = new URL(actionURL);
		InputStream is = url.openStream();
		File file = new File(newPath);
		if (!file.exists()) {
			File file2 = file.getParentFile();
			file2.mkdirs();
			file.createNewFile();
		}
		FileOutputStream bos = new FileOutputStream(file);

		byte[] fileByte = new byte[2048];
		int read = 0;
		while ((read = is.read(fileByte)) >= 0) {
			bos.write(fileByte, 0, read);
		}
		is.close();
		bos.close();
	}

	/**
	 * 删除文件
	 * 
	 * @param filePathAndName
	 *            文本文件完整绝对路径及文件名
	 * @return Boolean 成功删除返回true遭遇异常返回false
	 * @author YeQiangWei Studio by 我容易么我
	 */
	public static boolean delFile(String filePathAndName) {
		boolean bea = false;
			String filePath = filePathAndName;
			File myDelFile = new File(filePath);
			if (myDelFile.exists()) {
				myDelFile.delete();
				bea = true;
				logger.info("delete html is ok");
			} else {
				logger.info("HTML IS NOT EXITST");
				logger.info("delete html is fail");
				bea = false;
			}
		return bea;
	}

	public static void main(String[] args) throws Exception {
		FileInputStream stream = new FileInputStream("d:/we.txt");
		InputStreamReader reader = new InputStreamReader(stream);
		BufferedReader in = new BufferedReader(reader);
		byte[] buf = new byte[1024];
		int lengh = 0;
		while (stream.read(buf) > 0) {
			System.out.println(new String(buf));
		}
		// stream.read(buf);
		// System.out.println(buf.toString());
	}
}
